const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}


// 深复制对象和数组
function copy(data) {
  var obj = Array.isArray(data) ? [] : {};

  for (var name in data) {
    if (typeof data[name] === "object") { //先判断一下data[name]是不是一个对象
      obj[name] = Array.isArray(data[name]) ? [] : {}; //我们让要复制的对象的name项=数组或者是json
      obj[name] = copy(data[name]); //然后来无限调用函数自己 递归思想
    } else {
      obj[name] = data[name]; //如果不是对象，直接等于即可，不会发生引用。
    }
  }
  return obj; //然后在把复制好的对象给return出去
}
//覆盖对象，使用跟jq一样
function extend() {
  var obj = {};
  var arg = [].slice.call(arguments, 0);

  for (var i = 0, lenI = arg.length; i < lenI; i++) {
   
      for (var attr in copy(arg[i])) {
        if (checkType(arg[i][attr]) === '[object Object]') {
          obj[attr] = extend(arg[i][attr]);
        } else if (checkType(arg[i][attr]) === '[object Array]') {
          obj[attr] = [];
          for (var k = 0, lenK = arg[i][attr].length; k < lenK; k++) {
            if (checkType(arg[i][attr][k]) === '[object Object]') {
              obj[attr][k] = extend(arg[i][attr][k]);
            } else if (checkType(arg[i][attr][k]) === '[object Array]') {
              obj[attr][k] = [];
              obj[attr][k] = extend(arg[i][attr][k]);
            } else {
              obj[attr][k] = arg[i][attr][k];
            }
          }
        } else {
          obj[attr] = arg[i][attr];
        }
    }
  }
  return obj;
}
//非空数据，如空字符串、空数组、空对象
function isNotEmpty(v) {
  if (v === undefined) {
    return false;
  }

  if (v === null) {
    return false;
  }

  switch (checkType(v)) {
    case "[object String]":
      return v.replace(/\s*/g, "");
      break;
    case "[object Number]":
    case "[object Boolean]":
    case "[object Function]":
      return v;
      break;
    case "[object Array]":
      return v.length;
      break;
    case "[object Object]":
      return JSON.stringify(v).replace(/\s*/g, "") !== "{}"
      break;
  }
}

//判断类型，返回类似[object String]字符串数据
function checkType(val) {
  return Object.prototype.toString.call(val);
}

//延时函数-函数节流
var throttle = function(fn, interval) {
  var _self = fn; //保留函数
  var timer; //定时器
  var firstTime = true; //是否第一次执行
  return function() {
    var args = arguments;
    var _me = this;
    if (firstTime) { //如果是第一次就执行
      _self.apply(_me, args);
      return firstTime = false;
    }
    if (timer) { //如果定时器还在说明前一次还没执行完成
      clearTimeout(timer);
    }
    timer = setTimeout(function() {
      clearTimeout(timer);
      timer = null;
      _self.apply(_me, args);

    }, interval || 500)
  }
};

// 判断元素是否在数组里面
function inArray(search, array) {
  for (var i in array) {
    if (isNotEmpty(array[i]) && array[i] == search) {
      return true;
    }
  }
  return false;
}


/**
 * param 将要转为URL参数字符串的对象
 * key URL参数字符串的前缀
 * encode true/false 是否进行URL编码,默认为true
 * 
 * return URL参数字符串
 */
function urlEncode(param, key, encode) {
  if (param == null) return '';
  var paramStr = '';
  var t = typeof(param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
    paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};

function hasOffspringn(aData, id) {
  for (var i = 0; i < aData.length; i++) {
    if (aData[i].parentId == id) {
      return true;
    }
  }
  return false;
}

function getOffspringnTree(aData, pid) {
  var arr = [];

  for (var i = 0, lenI = aData.length; i < lenI; i++) {
    if (aData[i].parentId == pid) {
      let aFirst = aData[i];
      if (hasOffspringn(aData, aData[i].id)) {
        let a = getOffspringnTree(aData, aData[i].id) || [];
        if (a.length) {
          aFirst.children = a;
        }
      }
      arr.push(aFirst);
    }
  }
  return arr;
}


module.exports = {
  parseTime,
  formatTime,
  getOffspringnTree,
  hasOffspringn,
  copy,
  extend,
  isNotEmpty,
  throttle,
  inArray,
  urlEncode
};